<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Radar\Action\Sidebar;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\Utils\Media;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\Radar\Contract\RadarContract;

/**
 * 互动雷达媒体ID - 修改.
 *
 * Class Update.
 * @Controller
 */
class MediaIdUpdate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * @Inject
     * @var Media
     */
    protected $media;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/radar/mediaIdUpdate", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) != 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        // 参数验证
        $params = $this->request->all();
        $this->validated($params);

        $radar = $this->radarService->getRadarById((int) $params['id']);
        if (empty($radar)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '雷达不存在');
        }

        try {
            $mediaId = $this->media->upload($user['corpId'], 'file', $radar['pdf'], $radar['pdfName']);
        } catch (\Throwable $exception) {
            $mediaId = '';
        }
        return [
            'mediaId' => $mediaId,
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
